<template>
    <div style="min-width:809px">
        <div v-if="$route.path == '/personalAdmin/shiftManagement'">
            <div v-loading="loading" class="vs-search-box">
                <h4 class="flex align-centr">
                    门店:
                    <el-select v-model="store_id" @change="init" style="width:300px;margin-left:20px" placeholder="请选择">
                        <el-option
                            v-for="item in shopList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </h4>
                <el-descriptions :labelStyle="{'width':'140px'}" title="班次:" :column="1" border>
                    <!-- <template slot="extra">
                        <el-button type="primary" @click="dialogVisible=true" size="small">添加</el-button>
                    </template> -->

                    <el-descriptions-item v-for="item in shiftTypeArr" :key="item.id">
                        <template slot="label">
                            <div class="class-box">
                                <div class="color-zi" :style="{background:item.color}"></div>
                                {{item.title}}
                            </div>
                        </template>
                       <div class="right-box">
                            <span>
                                {{item.start_time}} -
                                {{item.is_tomorrow==1?'次日':''}}
                                {{item.stop_time}}
                            </span>
                            <!-- <span @click="setRow(1,item)" class="tab-table-text left-auto">编辑</span>
                            <span @click="setRow(2,item)" class="tab-red-text">删除</span> -->
                       </div>
                    </el-descriptions-item>

                    <el-descriptions-item label="成员自排班">
                        <el-checkbox @change="setStoreShift" v-model="is_sortNs">未排班时，允许成员自己选择班次打卡</el-checkbox>
                    </el-descriptions-item>
                    <el-descriptions-item label="调班申请">
                        <el-checkbox @change="setStoreShift" v-model="is_exchange">相同打卡规则的同事可申请，审批通过后自动调班</el-checkbox>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
            <div class="vs-table-box">
                <div class="operation-box ">
                    <div class="date-box"> 
                        <i @click="setMonth(-1)" class="iconfont el-icon-arrow-left" title="上一个月"></i>
                        <span>{{today}}</span>
                        <i @click="setMonth(1)" class="iconfont el-icon-arrow-right" title="下一个月"></i>
                    </div>
                    <div style="position: absolute; right: 20px;">
                        <!-- <el-button class="btn-upload" :loading="isDerive3" icon="el-icon-upload2" size="medium" >
                            <input ref="uploadPai" @change="shiftStatisticsImport" type="file" name="" id="">
                            导入排班
                        </el-button>
                        <el-button @click="derive" :loading="isDerive" icon="el-icon-download" size="medium" >导出排班</el-button> -->
                    </div>
                </div>
                <div class="table-box" v-loading="tabLog">
                    <table>
                        <thead>
                            <tr>
                                <th></th>
                                <th v-for="item in thead" :key="item.index">
                                    <div>{{item.day}}</div>
                                    <div>{{item.week}}</div>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- @click="setShiftVal(val,item,i)" -->
                            <tr v-for="(item) in tableData" :key="item.id" >
                                <td class="t1 no-line">{{item.name}}</td>
                                <td 
                                v-for="(val,i) in item.shift" 
                                :class="{
                                    'active-color':val.show,
                                    'td-disabled':val.disabled
                                }"
                                
                                :style="{background:val.types?val.types.color:'#aaaaaa'}"
                                :key="i">
                                    <span :style="colorText(val.types?val.types.color:'#aaaaaa')">
                                        {{val.types?val.types.title_text:''}}
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        
            <div class="vs-table-box">
                <div class="operation-box ">
                    <div style="position: absolute; right: 20px;">
                        <!-- <el-button icon="el-icon-upload2" size="medium" >导入排班</el-button> -->
                        <el-button @click="derive2" :loading="isDerive2" icon="el-icon-download" size="medium" >导出统计</el-button>
                    </div>
                </div>
                <div class="table-box" v-loading="loading2">
                    <table>
                        <thead>
                            <tr>
                                <th></th>
                                <th v-for="item in thead" :key="item.index">
                                    <div>{{item.day}}</div>
                                    <div>{{item.week}}</div>
                                </th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr v-for="(item,index) in dataList" :key="index">
                                <td class="t1 no-line">{{item.title}}</td>
                                <td 
                                v-for="(val,i) in item.data" 
                                :key="i">
                                    {{val}}
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        <router-view></router-view>
        <el-drawer
            title="我是标题"
            custom-class="drawer-color"
            size="250px"
            :modal="false"
            :visible.sync="drawer"
            :before-close="drawerClose"
            :with-header="false">
            <div v-loading="isBtn" class="drawer-classes">
                <div class="class-box" @click="setShift(item.id)" v-for="item in shiftList" :key="item.id">
                    <div class="color-zi" :style="{background:item.color}"></div>
                    {{item.title}}
                </div>
                <div class="class-box" @click="delShift()" >
                    <div class="color-zi" :style="{background:'#aaaaaa'}"></div>
                    休息
                </div>
            </div>
        </el-drawer>
        <el-dialog :title="`${form.id?'编辑':'新增'}班次`" width="615px" :visible.sync="dialogVisible" :before-close="handleClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
                <el-form-item label="班次标识：" prop="color">
                    <el-color-picker v-model="form.color"></el-color-picker>
                </el-form-item>
                <el-form-item label="班次名称：" prop="title">
                    <el-input style="width:100%" placeholder="请输入班次名称" v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="岗位类型：" prop="type">
                    <el-select v-model="form.type" placeholder="请选择岗位类型">
                        <el-option label="店长" :value="1"> </el-option>
                        <el-option label="前台" :value="2"> </el-option>
                        <el-option label="技师" :value="3"> </el-option>
                        <el-option label="办公室员工" :value="4"> </el-option>
                        <el-option label="其他" :value="10"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班次时间：" required >
                    <div class="banci-time">
                        <el-form-item prop="start_time" style="flex:1;">
                        <el-time-select
                            v-if="form.start_time||dialogVisible"
                            style="width:200px"
                            placeholder="起始时间"
                            v-model="form.start_time"
                            :picker-options="{
                                start: '00:00',
                                step: '00:30',
                                end: '23:30'
                            }">
                        </el-time-select>
                    </el-form-item>
                    <span class="text-center" style="padding:0 10px;white-space:nowrap;flex:1;">至{{isCi}}</span>
                    <el-form-item prop="stop_time" style="flex:1;">
                        <el-time-select
                        style="width:200px"
                            v-if="form.stop_time||dialogVisible"
                            placeholder="结束时间"
                            v-model="form.stop_time"
                            value-format="HH:mm:ss"
                            :picker-options="{
                                start: '00:00',
                                step: '00:30',
                                end: '23:30',
                                time:form.stop_time,
                            }">
                                <!-- minTime: form.startTime -->
                        </el-time-select>
                    </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                    <el-input-number v-model="form.sort" size="small" :step="1" step-strictly></el-input-number>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose()">取消</el-button>
                <el-button type="primary" :loading="isBtn" @click="shiftTypeAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            is_sortNs:false,//成员自排班
            is_exchange:false,//调班申请
            shopList:[],//门店列表
            store_id:'',//门店id
            shiftTypeArr:[],//班次类型
            drawer:true,//调班
            drawerHeight:0,
            yuanId:0,
            recordList: [],
            loading: false,
            loading2: false,
            tabLog:true,
            shiftLoad:false,
            isBtn: false,
            isInfo: false,
            dialogVisible: false,
            paging: {
                username: '',//姓名
                start_time: '',//开始时间
                end_time: '',//结束时间
                page: 1,
                total: 0,
                limit: 10,
            },
            form: {
                title: "",
                color:'',
                start_time:'',
                stop_time:'',
                is_tomorrow:0,
                sort:1,
                type:1,
                hour:0,
            },
            rules:{
                color :{ required: true, message: '请选择班次标识', trigger: 'change' },
                title:{ required: true, message: '请输入班次名称', trigger: 'blur' },
                type:{ required: true, message: '请选择岗位类型', trigger: 'change' },
                start_time: {  required: true, message: '请选择起始时间', trigger: 'change' } ,
                stop_time: { required: true, message: '请选择结束时间', trigger: 'change' }, 
            },
            tableData: [],
            dataList:[],
            shiftList:[],

            weekDayZh: ['日','一', '二', '三', '四', '五', '六'],
            thead:[],//表头
            is_sort:undefined,
            halfMonth:true,//前半月
            year:'',//当前年
            month:'',//当前月
            day:'',//当前日
            dayNum:0,//当前月有多少天
            isDerive:false,
            isDerive2:false,
            isDerive3:false,
        };
    },
    computed:{
        today(){//当前日期
            return `${this.year}年${this.month}月`;
        },
        detaTime(){
            let month = Number(this.month);
            return `${this.year}-${month>9?month:'0'+month}`
        },
        isCi(){
            let {start_time,stop_time} = this.form;
            if(stop_time&&start_time>stop_time){
                return '次日';
            }
            return '';
        }
    },
    async created() {
        if (this.$route.path == '/personalAdmin/shiftManagement') {
            let now = new Date();
            this.year = now.getFullYear();
            this.month = now.getMonth() + 1;
            this.day = now.getDate();
            // this.halfMonth = this.day<=15;
            await this.homegetStore();
            this.init();
        }
    },
    mounted(){
        this.drawer = false;
    },
    methods: {
        colorText(color){//背景自动配色
            let rgbs = this.utils.hexToRgb(color,false),
                threshold=0.55,
                sum = rgbs[0] + rgbs[1] + rgbs[2],
                lightness = sum / 255;
            return `color:hsl(0, 0%, calc(${(lightness - threshold) } * -999999% ));`
        },
        async derive(){
            this.isDerive = true;
            let res = await this.$Http.shiftExport({store_id:this.store_id,date:this.detaTime});
            this.utils.downloadXlsx(res,'员工排班');
            this.isDerive = false;
        },
        async derive2(){
            this.isDerive2 = true;
            let res = await this.$Http.shiftStatisticsExport({store_id:this.store_id,date:this.detaTime});
            this.utils.downloadXlsx(res,'排班统计');
            this.isDerive2 = false;
        },
        async shiftStatisticsImport(e){
            let file = e.target.files[0];
            if(!file)return;
            this.$refs.uploadPai.value = '';
            this.isDerive3 = true;
            let {code,data} = await this.$Http.shiftStatisticsImport({files:file},true);
            this.isDerive3 = false;
            if(code){
                this.$message.success('导入成功!');
                this.init();
            }
        },
        async delShift(){//排班改成休息
            this.isBtn = true;
            let {code} = await this.$Http.delShift({
                staff_id:this.yuanId,
                id:this.is_sort,
                // time:Date.parse(new Date(this.detaTime))/1000
            });
            this.isBtn = false;
            if(code){
                this.shiftTypeTg();
                this.drawerClose();
                this.staffshift();
            }
        },
        async shiftTypeTg(){//员工排版统计
            this.loading2 = true;
            // this.loading = true;this.store_id
            let {code,data} = await this.$Http.shiftTypeTg({store_id:this.store_id,date:this.detaTime});
            this.loading2 = false;
            console.log('员工排版统计',data);
            if(code){
                this.dataList = data;
            }
        },
        async setStoreShift(){//开关
            let {code,data} = await this.$Http.setStoreShift({
                store_id:this.store_id,
                is_sort:this.is_sortNs?1:0,
                is_exchange:this.is_exchange?1:0
            });
            if(code){

            }
        },
        async setShiftVal(val,item,i){
            if(!val.id)return this.$message.error('已超过调班天数!')
            this.drawer = true;
            val.show = true;
            this.is_sort = val.id;
            this.yuanId = item.id;
            this.isBtn = true;
            let {code,data} = await this.$Http.getShift({staff_id:item.id,store_id:this.store_id});
            this.isBtn = false;
            if(code){
                this.shiftList = data;
            }
        },
        drawerClose(dom){
            dom&&dom();
            this.drawer = false;
            this.is_sort = undefined;
            this.tableData = this.tableData.map(v=>{
                v.shift = v.shift.map(v2=>{
                    v2.show=false;
                    return v2;
                })
                return v;
            });

        },
        async setShift(id){//设置排班
            this.isBtn = true;
            let {code,data} = await this.$Http.setShift({
                type:id,
                id:this.is_sort,
            });
            this.isBtn = false;
            if(code){
                this.shiftTypeTg();
                this.drawerClose();
                this.staffshift();
            }
        },
        async staffshift(){//班次列表
            this.tabLog = true;
            let {code,data} = await this.$Http.staffshift({
                store_id:this.store_id,//
                date:this.detaTime
            });
            this.tabLog = false;
            if(code){
                if(!(data instanceof Array))data=[];
                let list = data.map(v=>{
                    v.shift = v.shift.map(v2=>{
                        v2.show=false;
                        if(!v2.types||v2.status==-1){
                            v2.types = v2.types?v2.types:{}
                            v2.types.color = '#f5f0f0';
                            v2.types.title_text = '休'
                        }
                        return v2;
                    })
                    return v;
                });
                let arr =[],leng = list.length?list[0].shift.length:0;
                // console.log(leng<this.dayNum,'leng<this.dayNum',leng,this.dayNum);
                // if(leng<this.dayNum){
                    console.log(this.dayNum ,leng,"差:",this.dayNum - leng);
                    for(let i = 0; i < this.dayNum;i++){
                        arr.push({
                            disabled:true,
                            show:false,
                            types:{
                                color:'#fff',
                                title_text:' '
                            }
                        })
                        // for(let val of list){
                        //     for(let vs of val.shift){
                        //         let time = new Date(vs.time*1000)
                        //         now.setDate(i+1);            //日
                        //         if(time!=now){
                        //             arr[i] = val;

                        //         }
                        //     }
                        // }
                    }
                // }
                console.log(arr,'listlistlist');
                // let now = new Date();
                this.tableData = list.map((v)=>{
                    let shift = [...arr];
                    for(let val of v.shift){
                        let time = new Date(val.time*1000)
                        let ri = time.getDate()
                        // now.setDate(ri);            //日
                        // if(time==now){
                            shift[ri-1] = val;
                        // }
                    }
                    v.shift = shift;
                    return v;
                });
                list.forEach(v=>{
                    v.shift.forEach(v2=>{
                        // console.log('v2',v2);
                    })
                })
                console.log(this.tableData,'this.tableData');
            }
        },
        async setRow(type,row){
            if(type==1){
                this.form = JSON.parse(JSON.stringify(row));
                this.dialogVisible = true;
            }else{
                this.$msgbox({
                    title: '提示',
                    message: '确定要该班次类型吗?',
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose:async (action, instance, done) => {
                        if (action === 'confirm') {
                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = '执行中...';
                        let {code,data} = await this.$Http.shiftTypeDel({ids:String(row.id)})
                            if(code){
                                this.$message.success('删除成功!');
                                this.init();
                            }
                            done();
                            instance.confirmButtonLoading = false;
                        } else {
                            done();
                        }
                    }
                }).then(action => {

                }).catch(()=>{});
            }
        },
        shiftTypeAdd(){//添加/修改班次类型
            this.$refs['form'].validate(async (valid) => {
                if (!valid) return;
                this.isBtn = true;
                let obj = Object.assign({},this.form);
                delete obj.create_time;
                delete obj.update_time;
                obj.is_tomorrow = this.isCi?1:0;
                if(obj.start_time.split(':').length==1){
                    obj.start_time+=":00";
                }
                if(obj.stop_time.split(':').length==1){
                    obj.stop_time+=":00";
                }
                obj.store_id = this.store_id;
                obj.hour = this.utils.dateStartEnd(obj.start_time,obj.stop_time,obj.is_tomorrow==1)

                let {code,data} = await this.$Http.shiftTypeAdd(obj);
                this.isBtn = false;
                if(code){
                    this.$message.success(obj.id?'修改成功':'添加成功');
                    this.handleClose();
                    this.staffshiftType();
                }
            });
        },
        async homegetStore(){//获取门店列表
            this.loading = true;
            let {code,data} = await this.$Http.homegetStore();
            if(code){
                this.shopList = data;
                this.store_id = data[0].id;
                this.is_sortNs = data[0].is_sort==1;//成员自排班
                this.is_exchange = data[0].is_exchange==1;//调班申请
            }else this.loading = false;
        },
        async staffshiftType(){//班次类型列表
            this.loading = true;
            let {code,data} = await this.$Http.staffshiftType({store_id:this.store_id});
            this.loading = false;
            if(code){
                this.shiftTypeArr = data;
            }
        },
        handleClose(dom){
            dom&&dom();
            this.dialogVisible = false;
            this.form = this.$options.data().form;
            // console.log(this.$refs.form,'this.$refs.form');
            this.$refs.form.resetFields();
        },
        setMonth(type){//设置月份
            let month = this.month + type;
            if(month>12){
                month = 1;
                this.year++;
            }else if(month<1){
                month = 12
                this.year--;
            }
            this.month = month;
            this.init();
        },
        async init(e) {//日期初始化
            if(e){
                let {is_sort,is_exchange} = this.shopList.find(v=>v.id==e);
                this.is_sortNs = is_sort==1;//成员自排班
                this.is_exchange = is_exchange==1;//调班申请
            }
            this.dayNum = this.getMonthDay(this.year,this.month);
            let week = this.getWeekday(this.year,this.month,'01');
            this.thead = [];
            for(let i=0;i<this.dayNum;i++){
                this.thead.push({
                    day:i+1,
                    week:this.weekDayZh[week],
                    index:i
                })
                week++;
                if(week>6)week=0;
            }

            this.staffshiftType();
            this.shiftTypeTg();
            this.staffshift();
            
            
        },
        //一个月有多少天
        getMonthDay(year, month) {
            let days = new Date(year, month, 0).getDate();
            return days;
        },
        getWeekday(year, month,day = '01') {//获取当月星期几
            let days = new Date(`${year}/${month}/${day} 00:00:00`).getDay();
            return days;
        },
        reset() {//重置
            this.paging = this.$options.data().paging;
            this.form.date = '';
            this.handleCurrentChange(1)
        },
    },
};
</script>

<style lang="scss" scoped>

.btn-upload{
    position: relative;
    overflow: hidden;
    input[type=file]{
        cursor:pointer;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
    }
    input[type=file]::-webkit-file-upload-button{
        cursor:pointer;
    }
}
::v-deep{
    .banci-time{
        display: flex;

        .el-form-item{
            flex: 1;
        }
    }
}
.td-disabled{
        background: linear-gradient(45deg, transparent 49.5%, #e9cddc 49.5%, #707070 50.5%, transparent 50.5%) !important;
    border: solid #a4a6a9;
    border-width: 0 1px 1px 0px;
}
::v-deep .el-drawer{
    // height: max-content;
    // top: calc(50% - 220px / 2);
    // top:50%;
    // transform: translateY(-50%);
    // padding: 30px;
    // border-radius:20px;
    height: max-content;
    margin: auto;
    right: 40px;
    display: flex;
    justify-content: center;
    box-shadow:none;
    background-color:inherit;
    overflow: initial;
    .el-drawer__body{
        flex: none;
        overflow: initial;
        height: max-content;
    }
    
}
.drawer-classes{
    background-color: #FFF;
    border-radius:20px;
    box-shadow: 0 8px 10px -5px rgb(0 0 0 / 20%), 0 16px 24px 2px rgb(0 0 0 / 14%), 0 6px 30px 5px rgb(0 0 0 / 12%);
    height: max-content;
    padding: 30px;
    ::v-deep{
        .el-loading-mask{
            border-radius:20px;
        }
    }
    .class-box{
        margin-bottom: 10px;
        cursor: pointer;
        &:hover .color-zi{
            box-shadow: rgb(45 45 45) 0px 1px 10px;
        }
    }
}
.vs-table-box{
    
    .operation-box{
        justify-content: space-between;
        min-height: 30px;
    }
    .date-box{
        margin: 0 auto;
        display: flex;
        align-items: center;
        span,i{
            font-weight: 600;
            font-size: 20px;
        }
        i{
            font-size: 25px;
            padding: 0 5px;
            cursor: pointer;
        }
    }
    .table-box{
        min-height: 200px;
        overflow: auto;
        position: relative;
    }
    table{
        width: 100%;
        border: solid #ebeef5;
        border-width: 1px 0 0 1px;
        border-collapse: collapse;
        border-spacing: 0;
        thead{
            th{
                padding: 10px 20px;
                font-weight: 700;
                color: #909399;
                background: #fafafa;
                div{
                    &:nth-child(1){
                        font-weight: 300;
                    }
                }
            }
        }
        .t1{
            position: sticky;
            left: 0;
            background: #fff;
            z-index: 99;
        }
        .t1,tfoot td,thead th{
            border: solid #ebeef5;
            border-width: 0 1px 1px 0px;
        }
        // .t1{//暂时放弃
        //     position: sticky;
        //     left: 0;
        //     z-index: 92;
        //     background: #fff;
        //     border-left: 1px solid #ebeef5;
        // }
        .active-color{
            transform: scale(1.2);
            // /* border: 1px solid red !important; */
            box-shadow: #ffffff 1px -1px 6px 4px;
            z-index: 999;
            position: absolute;
            // color: red;
            
        }
        td{
            color: #000000;
            // text-shadow: 1px 1px 5px #ffffff;
            transition:all 0.3s;
        }
        tbody{
            tr{
                td{
                    cursor: pointer;
                    user-select: none;
                    position: relative;
                    // span{
                    //     position: absolute;
                    //     z-index: 99;
                    //     transform: translate(-50%,-50%);
                    // }
                    // &:not(:nth-child(1)){
                        // text-shadow: 0px 0px 5px #ffffff;
                        // &:before{
                        //     // z-index: 1;
                        //     content: '';
                        //     position: absolute;
                        //     top: 50%;
                        //     left: 50%;
                        //     transform: translate(-50%,-50%);
                        //     // background: #fff;
                        //     box-shadow: 0px 0px 30px 11px rgb(255 255 255);
                        //     // width: 10px;
                        //     // height: 10px;
                        // }
                    // }
                }
            }
        }
        th,td{
            
            padding: 20px;
            text-align: center;
        }
    }
}
.class-box{
    display: flex;
    align-items: center;
    .color-zi{
        width: 30px;
        height: 30px;
        border-radius: 50%;
        margin-right: 10px;

    }
}
.vs-search-box{
    .right-box{
        display: flex;
        align-items: center;
    }
}
::v-deep{
    .el-descriptions .is-bordered td, .el-descriptions .is-bordered th{
        border:none;
    }
    .el-descriptions-item__label.is-bordered-label{
        background: #0000;
    }
}
</style>